<template>
  <div class="chart chartborder" :class="'imp'+cBorderColor">
    <ImpBorder></ImpBorder>
    <div class="chart-header" >
        <p class="title">
            <span>{{currentData.title}}</span>
            <cite class="titleActive"></cite>
        </p>
        <div class="select">
            <el-dropdown  @command="handleSelectChange" trigger="click" v-if="cData.length > 1">
                <span class="el-dropdown-link" style="cursor:pointer">
                    {{currentSelectName}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                        v-for="item in cData"
                        :value="item.label.value"
                        :key="item.label.value"
                        :command="item"
                        >
                            {{item.label.name}}
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </div>
    <div class="chart-container">
      <!-- {{currentData.extent?'chartExtent':'chartExtend'}}
      {{currentData.extent}} -->
     <!-- ||  JSON.stringify(currentData.data.rows)!=='{}' -->
      <component
        :is="currentView"
        height='100%'
        :judge-width="true"
        :data="currentData.data"
        :extend="chartExtend"
        :settings="currentData.type== 'wordcloud' ? {'color':curColor} : currentData.settings"
        :colors="curColor"
        :dataZoom="curDataZoom"
        :tooltip="currentData.tooltip"
        :legend="currentData.legend?currentData.legend:legendOption"
        :after-set-option="afterSetOption"
      >
        <!-- :extend="currentData.extent?chartExtent:chartExtend" -->


      <!-- :data-empty="currentData.data.rows.length == 0 ? true : false" -->
        <!-- <div class="data-empty" v-if="currentData.data.rows.length == 0 && cBorderColor == 1">无用地腾退</div>
        <div class="data-empty" v-if="currentData.data.rows.length == 0 && cBorderColor == 3">无违建拆除</div>
        <div class="data-empty" v-if="currentData.data.rows.length == 0 && cBorderColor == 2" >无人口变化</div>
        <div class="data-empty" v-if="currentData.data.rows.length == 0 && cBorderColor == 4">无企业变化</div> -->
      </component>
      <!-- 解决散点图数据为空的情况 -->
      <!-- currentData.data.rows instanceof Array ? (currentData.data.rows.length > 0 ? false : true) : (JSON.stringify(currentData.data.rows) === '{}' ? true : false) -->
      <!-- :before-config="beforeConfig"
        :after-config="afterConfig" -->
      <!-- :legend="currentData.legend" -->
      <!-- currentData.data.rows.length > 9 && currentData.type=='histogram' ? curDataZoom : [] -->
      <!-- :after-set-option="afterSetOption" -->
    </div>
  </div>
</template>
<script>
import echarts from 'echarts'
import ImpBorder from '@/components/ImpBorder'
import veLine from 'v-charts/lib/line.common'
import veHistogram from 'v-charts/lib/histogram.common'
import vePie from 'v-charts/lib/pie.common'
import veWordcloud from 'v-charts/lib/wordcloud.common'
import veBar from 'v-charts/lib/bar.common'
import veRing from 'v-charts/lib/ring.common'
import veScatter from 'v-charts/lib/scatter.common'

export default {
  components: {
    ImpBorder
  },
  props: {
    cData: {
      type: Array,
      default: () => []
    },
    cBorderColor: {
      type: Number,
      default: 0
    }
  },
  data () {
    this.chartExtendOther = {
        series: data => {
          data.map( (item, idx) => {
            // 根据第一个值
            item['label'] = item['data'][0]>0
                            ? { show: true, position: "top", color:'#fff'}
                            : { show: true, position: "bottom", color:'#fff'}

            item['animationDelay'] = idx * 60
            item['barGap'] = 0
            item['barMaxWidth'] = '40%'
            item['animationDelay'] = function (idx) {
              // 越往后的数据延迟越大
              return idx * 60
            }
          })
          return data
        },

        grid: {
          top: 20,
          left: 40,
          bottom: 60,
          right: 40,
          containLabel: true
        },
        legend: {
          show: true,
          bottom:0
        },
        xAxis: {
          offset: 10,
          axisLabel: {
            color: '#aaa'
            // interval: 1
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#aaa'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          nameTextStyle: {
            color: '#aaa'
          },
          axisLabel: {
            show: false
          },
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        }

      }

    return {
      dataIndex: 0,//每一行=》每一列=》每一组中的每一个
      currentSelectName: '', // 下拉名称
      view: '', // 图表的每个实例
      rules: {
        line: veLine,
        histogram: veHistogram,
        pie: vePie,
        wordcloud: veWordcloud,
        bar: veBar,
        ring: veRing,
        scatter: veScatter
      },
      // 图例暂时不用滚动
      legendOption: {
        icon: 'rect',
        textStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        pageIconColor: '#aaa',
        pageIconInactiveColor: '#2f4554',
        type: 'scroll',
        pageIconSize: [15, 15],
        bottom: 5,
        width: '84%',
        orient: 'horizontal',
        itemWidth: 12,
        itemHeight: 10,
        itemGap: 5
      },
      extendsOption: {
        //   图表相同的基本配置
        baseSeries: {
          grid: {
            top: 15,
            left: 40,
            bottom:50,
            right: 40,
            containLabel: true
          },
          legend: {
            show: true,
            bottom:0
          },
          xAxis: {
            axisLabel: {
              color: '#aaa'
              // interval: 1
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            nameTextStyle: {
              color: '#aaa'
            },
            axisLabel: {
              show: false
            },
            axisLine: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          series: {
            // barMaxWidth: 30,
            label: { show: true,  color: '#fff' },
            animationDelay: function (idx) {
              // 越往后的数据延迟越大
              return idx * 60
            },
            barGap: 0 // 不同一系列柱图间距
          }

        },
        // 图表个别属性配置
        specialSeries: {
          line: {
            grid: {
              top: 30,
              left: 40,
              bottom: 30,
              right: 40,
              containLabel: true
            },
            legend:{
              show:true
            },
            // xAxis:{
            //   boundaryGap: false
            // },
            series: {
              label: { show: true,  position: 'top',color: '#fff' }
            }
          },
          scatter: {
            grid: {
              top: 30,
              left: 30,
              bottom: 50,
              right: 45,
              containLabel: true
            },
            xAxis: {
              axisLabel: {
                color: '#fff'
                // interval: 1
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#fff'
                }
              },
              splitLine: {
                show: false
              },
              axisTick: {
                show: false
              }
            },
            yAxis: {
              axisLabel: {
                color: '#fff'
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#fff'
                }
              },
              splitLine: {
                show: false
              },
              axisTick: {
                show: false
              }
            }
          },
          bar: {
            grid: {
              top: 5,
              left: 30,
              bottom: 5,
              right: 30,
              containLabel: true
            },
            legend: {
              show: false
            },
            xAxis: {
              show: false
            },
            yAxis: {
              axisLabel: {
                show: true,
                color: '#fff',
                interval: 0
              }
            },
            series: {
              label: { show: true, position: 'right', color: '#fff' }
            }
          },
          pie: {
            legend: {
              show: false,
              icon: 'rect',
              textStyle: {
                color: '#fff',
                fontSize: 12
              },
              pageIconColor: '#ddd',
              pageIconInactiveColor: '#aaa',
              pageTextStyle: {
                color: '#ddd'
              },
              type: 'scroll',
              pageIconSize: [15, 15],
              bottom: 5,
              width: '84%',
              orient: 'horizontal',
              itemWidth: 12,
              itemHeight: 10,
              itemGap: 5
              // orient: 'vertical',
              // show: true,
              // x: '63%',
              // y: 'center'
            }
          },
          ring: {
            title: {
              text: '17.7',
              subtext: '进度50%...',
              x: 'center',
              y: 'center',
              textStyle: {
                fontWeight: 'normal',
                color: '#ffc612',
                fontSize: '30'
              }
            },
            legend: {
              show: false,
              orient: 'vertical',
              icon: 'circle',
              x: '70%',
              y: 'center',
              textStyle: {
                color: '#fff'
              }
            },
            series: {
              center: ['50%', '50%'],
              radius: [60, 70],
              label: {
                show: false
              },
              labelLine: {
                show: false
              }
            }
          }
        }
      }
    }
  },
  methods: {
    handleSelectChange (item) {
      this.currentSelectName = item.label.name
      this.cData.forEach((element, index) => {
        if (element.label.name == this.currentSelectName) {
          this.dataIndex = index
        }
      })
    },
    afterSetOption (initstance) {
      // let option = initstance.getOption()
      // initstance.clear()// 清掉 才会重绘 有动画
      // initstance.setOption(option)
      initstance.resize()
    },
    booleanFormat (obj) {
      let self = this
      // 折线横纵轴及spitline分割线 后台传过来的是字符串"false" 解决完成
      if ('xAxis' in obj) {
        if ('axisLine' in obj.xAxis) {
          obj.xAxis.axisLine.show = false
        }
        if ('axisTick' in obj.xAxis) {
          obj.xAxis.axisTick.show = false
        }
        if ('splitLine' in obj.xAxis) {
          obj.xAxis.splitLine.show = false
        }
        if ('boundaryGap' in obj.xAxis) {
          obj.xAxis.boundaryGap = false
        }
      }
      // 折线面积图线性渐变
      obj.areaStyle = {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: self.curColor[0]
        }, {
          offset: 1,
          color: 'rgba(255, 255, 255, .2)'
        }]
        )
      }
      return obj
    },
    getCurrentView () {
      if (this.cData[this.dataIndex].type) {
        this.view = this.rules[this.cData[this.dataIndex].type] || null
      }
    },
    // 渐变颜色方法(从上到下)
    gradiantColor (direction) {
      let arr = [0, 1]
      let x
      let tempTop = Object.assign({}, this.extendsOption.baseSeries, {
        series: {
          barGap: 0.5,
          barMaxWidth: 30,
          label: { show: true, position: 'top', color: '#fff' },
          animationDelay: function (idx) {
            // 越往后的数据延迟越大
            return idx * 60
          },
          itemStyle: {
            normal: {
              color: (val) => {
                if (val.seriesIndex == 0) {
                  return new echarts.graphic.LinearGradient(
                    0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: this.curColor[0]
                      },
                      {
                        offset: 1,
                        color: 'rgba(255, 255, 255, .2)'
                      }
                    ]
                  )
                } else {
                  return new echarts.graphic.LinearGradient(
                    0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: this.curColor[7]
                      },
                      {
                        offset: 1,
                        color: 'rgba(255, 255, 255, .2)'
                      }
                    ]
                  )
                }
              }
            }
          }
        }
      })

      let tempLeft = Object.assign({}, this.extendsOption.baseSeries, {
        series: {
          itemStyle: {
            normal: {
              barBorderRadius: 16,
              color: {
                type: 'linear',
                x: 0,
                x1: 1,
                colorStops: [{
                  offset: 0,
                  color: this.curColor[this.cBorderColor]
                }, {
                  offset: 1,
                  color: 'rgba(255, 255, 255, .2)'
                }]
              }
            }
          }
        }
      })
      if (direction == 'left') {
        return tempLeft
      } else if (direction == 'top') {
        return tempTop
      }
    },
    // 饼图边框主题颜色
    pieBorderColor () {
      let themeColor = Object.assign({}, this.extendsOption.specialSeries.pie, {
        series: {
          radius: '85%',
          center: ['50%', '50%'],
          itemStyle: {
            normal: {
              borderColor: this.curColor[this.cBorderColor],
              // borderWidth: 1,
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(30, 144, 255，0.5)'
              },
              color: (params) => {
                let colorarr = []
                let namelist = ['仓储', '办公', '公共管理与公共服务设施用地',
                  '居住', '居住用地', '住宅', '工业', '产业用地', '商业', '其他', '其它', '养殖', '蔬菜大棚', '道路用地',
                  '交通设施用地', '对外交通用地', '对外交通设施用地', '市政设施用地', '绿地与广场用地', '城市水域', '其他建设用地',
                  '战略留白用地', '林草保护用地', '生态混合用地', '自然保留地', '特殊用地',
                  '永久基本农田', '永久基本农田储备用地', '水域沟渠', '水工建筑用地', '水库水面', '', '未知'
                ]
                if (namelist.indexOf(params.name) > -1) {
                  switch (params.name) {
                    case '仓储':
                      params.color = 'rgb(153,102,204)'
                      colorarr.push(params.color)
                      break
                    case '办公':
                      params.color = 'rgb(255,123,156)'
                      colorarr.push(params.color)
                      break
                    case '公共管理与公共服务设施用地':
                      params.color = 'rgb(255,0,63)'
                      colorarr.push(params.color)
                      break
                    case '居住':
                    case '居住用地':
                      params.color = 'rgb(255,255,0)'
                      colorarr.push(params.color)
                      break
                    case '住宅':
                      params.color = 'rgb(255,191,0)'
                      colorarr.push(params.color)
                      break
                    case '工业':
                    case '产业用地':
                      params.color = 'rgb(153,114,76)'
                      colorarr.push(params.color)
                      break
                    case '商业':
                      params.color = 'rgb(255,0,0)'
                      colorarr.push(params.color)
                      break
                    case '其他':
                    case '其它':
                    case '其他建设用地':
                      params.color = 'rgb(0,63,127)'
                      colorarr.push(params.color)
                      break
                    case '养殖':
                      params.color = 'rgb(220,180,130)'
                      colorarr.push(params.color)
                      break
                    case '蔬菜大棚':
                      params.color = 'rgb(131,194,56)'
                      colorarr.push(params.color)
                      break
                    case '道路用地':
                    case '交通设施用地':
                    case '对外交通用地':
                    case '对外交通设施用地':
                      params.color = 'rgb(128,128,128)'
                      colorarr.push(params.color)
                      break
                    case '市政设施用地':
                      params.color = 'rgb(127,191,255)'
                      colorarr.push(params.color)
                      break
                    case '绿地与广场用地':
                      params.color = 'rgb(0,255,0)'
                      colorarr.push(params.color)
                      break
                    case '城市水域':
                      params.color = 'rgb(127,255,255)'
                      colorarr.push(params.color)
                      break
                    case '战略留白用地':
                      params.color = 'rgb(153,153,76)'
                      colorarr.push(params.color)
                      break
                    case '林草保护用地':
                      params.color = 'rgb(120,220,120)'
                      colorarr.push(params.color)
                      break
                    case '生态混合用地':
                      params.color = 'rgb(40,110,25)'
                      colorarr.push(params.color)
                      break
                    case '自然保留地':
                      params.color = 'rgb(180,180,180)'
                      colorarr.push(params.color)
                      break
                    case '特殊用地':
                      params.color = 'rgb(130,130,130)'
                      colorarr.push(params.color)
                      break
                    case '永久基本农田':
                      params.color = 'rgb(110,170,0)'
                      colorarr.push(params.color)
                      break
                    case '永久基本农田储备用地':
                      params.color = 'rgb(255,170,0)'
                      colorarr.push(params.color)
                      break
                    case '水域沟渠':
                      params.color = 'rgb(0,135,255)'
                      colorarr.push(params.color)
                      break
                    case '水工建筑用地':
                      params.color = 'rgb(70,130,180)'
                      colorarr.push(params.color)
                      break
                    case '水库水面':
                      params.color = 'rgb(115,255,255)'
                      colorarr.push(params.color)
                      break
                    case ' ':
                    case '未知':
                      params.color = 'rgb(255,255,255)'
                      colorarr.push(params.color)
                      break
                    default:
                      break
                  }
                  return colorarr
                } else {
                  return this.curColor[params.dataIndex]
                }
              }
            }
          },
          label: {
            normal: {
              show: false
              // position: 'inner',
              // formatter: '{c}',
              // textStyle: {
              //     color: '#fff',
              //     fontWeight: 'bold',
              //     fontSize: 14
              // }
            }
          }
        }
      })
      return themeColor
    }
  },
  computed: {
    // 对于有extent的图表判断(目前针对：散点 折线面积)
    chartExtent () {
      let chartExtent = ''
      if (this.cData[this.dataIndex].type == 'scatter') {
        if (JSON.stringify(this.currentData.data.rows) !== '{}') {
          // 散点图不为空时 合并extent(平均线)
          let specialExtent = this.extendsOption.specialSeries[this.cData[this.dataIndex].type] || {}
          chartExtent = Object.assign({}, specialExtent, this.booleanFormat(this.currentData.extent))
        } else {
          // 如果散点图为空 为baseExtends
          chartExtent = this.baseExtends
        }
      } else {
        chartExtent = Object.assign({}, this.baseExtends, this.booleanFormat(this.currentData.extent))
        // console.log(chartExtent)
      }
      return chartExtent
    },
    // 指标监测
    curindex () {
      return this.$store.getters.curindex
    },
    curColor () {
      return this.$store.getters.curColor
    },
    currentView () {
      return this.view
    },
    // 图表extend属性的基本配置和特殊配置
    chartExtend () {
      let extend
      let curtype = this.cData[this.dataIndex].type
      let that = this
      if (curtype == 'histogram') {
        extend = this.chartExtendOther

      } else if (curtype == 'bar') {
        extend = this.gradiantColor('left')
      } else if (curtype == 'pie') {
        extend = this.pieBorderColor()
      } else if(curtype == 'line'){
        extend = this.baseExtends
        extend.grid.top = 20
        extend.grid.bottom = 55
      } else {
        extend = this.extendsOption.specialSeries[this.cData[this.dataIndex].type] || {}
      }
      return extend
    },
    // 返回的每一个对象
    currentData () {
      return this.cData[this.dataIndex] || {}
    },
    curDataZoom () {
      let datazoom = []
      let histype = this.currentData.type
      let isHisDatazoom = this.currentData.title;
      let columnslength = this.currentData.data.columns.length
      let rowslength = this.currentData.data.rows.length
      let datazoomobj =  { 
        type: 'slider',
        start: 0,  
        height: 15, 
        textStyle: { color: '#a9adb7' }, 
        zoomLock: true
      }
      
      if (histype == 'histogram'){
        // 多余10条加zoom
        if(rowslength >= 10){
          // 计算系数600，数值越大，柱子约密；数值越小，柱子越稀疏
          datazoomobj.end = 600 / rowslength 
          datazoom = datazoomobj
        }
        // 多组柱图，控制x轴文字标注
        if(columnslength >= 2){
          // console.log(this.currentData)
          // this.currentData.extent.xAxis.offset = 10
        }
      }

      return datazoom
    },
    baseExtends () {
      return this.extendsOption.baseSeries
    }
  },
  watch: {
    curindex (val) {
      this.$nextTick(() => {
        // 监听指标变化时重新渲染每个图表实例
        this.getCurrentView()
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      //   判断是为了解决chartdata的select（没有下拉数据时，不添加label字段）
      if (this.currentData.label) {
        this.currentSelectName = this.cData[this.dataIndex].label.name
      }
      // 调用当前图表实例
      this.getCurrentView()
    })
  }
}
</script>

<style lang="stylus" scoped>
/* 每个图表样式 */
.chart
    width 100%
    height 100%
    position relative

    .chart-header
        position relative

        .title
            // 解决多个图表标题问题
            height 30px
            line-height 30px
            padding 6px 0 6px 25px
            color #fff
            font-size 14px
            font-weight 500

            span
                // white-space nowrap

            cite.titleActive
                position absolute
                left 15px
                top 12px
                width 3px
                height 17px
                // background #13ffd7

        .select
            position absolute
            right 8px
            top 32px
            bottom 0
            z-index 40
            .el-dropdown
                color #d2d2d2!important
                font-size 14px

    .chart-container
        width 100%
        overflow hidden
        height calc(100% - 42px)

// 饼图下拉框
.el-dropdown-menu
  background #000!important
  opacity 0.8!important
  border 1px solid #333

.el-dropdown-menu.el-popper[x-placement^=bottom] /deep/  .popper__arrow
  border-bottom-color #000!important
.el-dropdown-menu.el-popper[x-placement^=bottom] /deep/  .popper__arrow::after
  border-bottom-color #000!important

.el-dropdown-menu__item
  color #fff!important

.el-dropdown-menu__item:focus, .el-dropdown-menu__item:not(.is-disabled):hover
  background-color #666

// 暂无数据的状态
.chart-container /deep/ .v-charts-data-empty
  position absolute!important
  left calc(50% - 24px)!important
  top calc(50% - 30px)!important
</style>
